题目要求
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.
However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.
Example:
n = 10, I pick 8.
First round: You guess 5, I tell you that it's higher. You pay $5.
Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round: You guess 9, I tell you that it's lower. You pay $9.
Game over. 8 is the number I picked.
You end up paying $5 + $7 + $9 = $21.
Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.
一个猜数字游戏,数字区间为1~n,每猜一次,会有人告诉你猜中了或者当前的数字是大于结果值还是小于结果值。猜对则本次猜测免费,猜错则本次猜测需要花费和数字等额的金钱。
问如果要确保能够猜中数字,最少要花费多少钱。
其实这题的英文表述有些问题,确切来说,在所有能够确保找到目标值的方法中,找到花费金钱最少的哪种。
思路
我们先用一个比较简单的数字来找规律。当n等于3时,即从1,2,3
中找到目标数字,确保找到一个数字至少需要多少钱。
查询序列如下:
- 目标值3:
1,2
2
- 目标值2:
1,3
- 目标值1:
3,2
,2
可见如果要找到1,2,3中任意一个数字,最少要花费2元钱,即从2开始查询,如果命中,则花费0元,如果没有命中也知道目标值比2小还是比2大,下次猜测一定命中,因此该序列中找到任何一个数字最多花费2元钱。
如此可见,假如要知道min(1,n)的值,只要找到花费最小的中间点k,即递归的公式相当于min(1,n) = k + Math.max(min(1, k-1), min(k+1,n)) 1<=k<=n
找到最小的min即可。
思路一:自顶向下的动态规划
public int getMoneyAmount(int n) {
int[][] tmp = new int[n+1][n+1];
for(int[] row: tmp){
Arrays.fill(row, Integer.MAX_VALUE);
}
return getMoneyAmount(n, 1, n, tmp);
}
public int getMoneyAmount(int n, int lft, int rgt, int[][] tmp) {
if(lft>=rgt) return 0;
if(tmp[lft][rgt] != Integer.MAX_VALUE) return tmp[lft][rgt];
for(int i = lft ; i<=rgt ; i++) {
tmp[lft][rgt] = Math.min(tmp[lft][rgt], Math.max(i + getMoneyAmount(n, lft, i-1, tmp), i + getMoneyAmount(n, i+1, rgt, tmp)));
}
return tmp[lft][rgt];
}
思路二:自底向上的动态规划
public int getMoneyAmount(int n) {
int[][] dp = new int[n+1][n+1];
for(int i = 2 ; i<=n ; i++) {
for(int j = i-1 ; j>0 ; j--) {
int min = Integer.MAX_VALUE;
for(int k = j+1 ; k<i ; k++) {
min = Math.min(min, k + Math.max(dp[j][k-1], dp[k+1][i]));
}
dp[j][i] = j + 1 == i ? j : min;
}
}
return dp[1][n];
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。